import socket
import os
import hashlib
import sqlite3
import re
import time
import pymysql
def alert(url_blacklist,type):
    attack_IP = url_blacklist.split(' ')[0]
    if attack_IP == "::1":
        attack_IP = "127.0.0.1"
    time_log = re.findall(r"\[(.+?) +", url_blacklist)[0]  # 判断时间戳
    db_url = re.findall(r"\](.+?) HTTP", url_blacklist)[0]  # 判断URL
    # conndb = sqlite3.connect("user_information.db")
    # cur = conndb.cursor()
    # cur.execute('''CREATE TABLE IF NOT EXISTS warning_web_information(
    #     attack_type  TEXT,
    #     IP   TEXT,
    #     time_log TEXT,
    #     URL TEXT);''')
    # conndb.commit()
    db = pymysql.connect(
        host='localhost',
        user='root',
        password='123456',
        database='maoxuechunqimozuoye'
    )
    py_cursor = db.cursor()
    py_cursor.execute('''CREATE TABLE IF NOT EXISTS warning_web_information(
            attack_type  varchar(256),
            IP   varchar(256),
            time_log varchar(256),
            URL varchar(256))DEFAULT CHARSET=utf8;''')
    db.commit()

    if type==0:
        py_cursor.execute(f"INSERT INTO warning_web_information(attack_type,IP,time_log,URL) values('{'SQL注入'}','{attack_IP}','{time_log}','{db_url}')")

    if type==1:
        py_cursor.execute(f"INSERT INTO warning_web_information(attack_type,IP,time_log,URL) values('{'XSS'}','{attack_IP}','{time_log}','{db_url}')")

    if type==2:
        py_cursor.execute(f"INSERT INTO warning_web_information(attack_type,IP,time_log,URL) values('{'web登录暴力破解'}','{attack_IP}','{time_log}','{db_url}')")

    db.commit()
    db.close()

def web_IDS(conn,file_name,file_size):
    f = open("Web_log/" + file_name, "wb")
    conn.send("准备好接收".encode("utf-8"))  # 确认接收

    received_size = 0

    while received_size < file_size:
        if file_size - received_size > 1024:
            size = 1024
        else:
            size = file_size - received_size  # 最后一次接收

        data = conn.recv(size)  # 多次接收
        data_len = len(data)
        received_size += data_len
        f.write(data)
    f.close()
    conn.send("4".encode("utf-8"))  # 确认接收4
    f_log_r = open("Web_log/" + file_name, "r")
    url_data = f_log_r.readlines()

    with open('static/rules/XSS.txt', 'r') as file:
        XSS_Check = file.readlines()
    with open('static/rules/SQL.txt', 'r') as file:
        SQL_Check = file.readlines()
    with open('static/rules/brute_log.txt', 'r') as file:
        BRUTE_Check = file.readlines()
    for one_url in url_data:  # 判断XSS
        for xss in XSS_Check:
            if xss.split('\n')[0].lower() in one_url:
                url_blacklist = one_url
                type = 1  # xss
                alert(url_blacklist, type)
                break

    for one_url in url_data:  # 判断SQL
        for sql in SQL_Check:
            if sql.split('\n')[0].lower() in one_url:
                url_blacklist = one_url
                type = 0  # SQL
                alert(url_blacklist, type)
                break

    str_brute = "POST /pikachu-master/pkxss/pkxss_login.php"
    burp_list = []
    for one_url in url_data:  # 判断暴力破解
        if str_brute in one_url:
            burp_list.append(one_url)
            if len(burp_list) > 5:
                type = 2  # 暴力破解
                alert(one_url, type)
                burp_list = []

    for one_url in url_data:  # 导入日志
        web_IP = one_url.split(' ')[0]
        if web_IP == "::1":
            web_IP = "127.0.0.1"
        time_log = re.findall(r"\[(.+?) +", one_url)[0]  # 判断时间戳
        db_url = re.findall(r"\](.+?) HTTP", one_url)[0]  # 判断URL
        # sqlite_conn = sqlite3.connect("user_information.db")
        # cur = sqlite_conn.cursor()
        # cur.execute('''CREATE TABLE IF NOT EXISTS log_web_information(
        #                         IP   TEXT,
        #                         time_log TEXT,
        #                         URL TEXT);''')
        # sqlite_conn.commit()
        # cur.execute(f"INSERT INTO  log_web_information(IP,time_log,URL) values('{web_IP}','{time_log}','{db_url}')")
        # sqlite_conn.commit()
        # sqlite_conn.close()

        db = pymysql.connect(
            host='localhost',
            user='root',
            password='123456',
            database='maoxuechunqimozuoye'
        )
        py_cursor = db.cursor()
        py_cursor.execute('''CREATE TABLE IF NOT EXISTS log_web_information(
                                        IP   TEXT,
                                        time_log TEXT,
                                        URL TEXT)DEFAULT CHARSET=utf8;''')
        db.commit()
        py_cursor.execute(f"INSERT INTO  log_web_information(IP,time_log,URL) values('{web_IP}','{time_log}','{db_url}')")
        db.commit()
        db.close()
    f_log_r.close()